// app.js
App({
  globalData: {
    userInfo: null,
    token: null,
    baseUrl: 'http://localhost:5500/api', // 开发环境
    // baseUrl: 'https://your-domain.com/api', // 生产环境
  },

  onLaunch() {
    // 检查登录状态
    this.checkLoginStatus()
  },

  onShow() {
    // 小程序显示时的逻辑
  },

  onHide() {
    // 小程序隐藏时的逻辑
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    const userInfo = wx.getStorageSync('userInfo')
    
    if (token && userInfo) {
      this.globalData.token = token
      this.globalData.userInfo = userInfo
    }
  },

  // 微信登录
  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            this.loginWithCode(res.code)
              .then(resolve)
              .catch(reject)
          } else {
            reject(new Error('微信登录失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 使用code登录
  loginWithCode(code) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.globalData.baseUrl}/auth/wechat/login`,
        method: 'POST',
        data: {
          code: code
        },
        success: (res) => {
          if (res.data.success) {
            const { access_token, refresh_token, user } = res.data.data
            
            // 保存token和用户信息
            this.globalData.token = access_token
            this.globalData.userInfo = user
            wx.setStorageSync('token', access_token)
            wx.setStorageSync('refresh_token', refresh_token)
            wx.setStorageSync('userInfo', user)
            
            resolve(user)
          } else {
            reject(new Error(res.data.message || '登录失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 获取用户信息
  getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          resolve(res.userInfo)
        },
        fail: reject
      })
    })
  },

  // 请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      const token = this.globalData.token
      
      wx.request({
        url: `${this.globalData.baseUrl}${options.url}`,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : '',
          ...options.header
        },
        success: (res) => {
          if (res.statusCode === 401) {
            // token过期，尝试刷新
            this.refreshToken()
              .then(() => {
                // 重新发起请求
                this.request(options).then(resolve).catch(reject)
              })
              .catch(() => {
                // 刷新失败，跳转登录
                this.logout()
                reject(new Error('登录已过期'))
              })
          } else if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data)
          } else {
            reject(new Error(res.data.message || '请求失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 刷新token
  refreshToken() {
    return new Promise((resolve, reject) => {
      const refresh_token = wx.getStorageSync('refresh_token')
      
      if (!refresh_token) {
        reject(new Error('无刷新token'))
        return
      }

      wx.request({
        url: `${this.globalData.baseUrl}/auth/refresh`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${refresh_token}`
        },
        success: (res) => {
          if (res.data.success) {
            const { access_token } = res.data.data
            this.globalData.token = access_token
            wx.setStorageSync('token', access_token)
            resolve()
          } else {
            reject(new Error('刷新token失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 登出
  logout() {
    this.globalData.token = null
    this.globalData.userInfo = null
    wx.removeStorageSync('token')
    wx.removeStorageSync('refresh_token')
    wx.removeStorageSync('userInfo')
    
    // 跳转到登录页或首页
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },

  // 显示提示
  showToast(title, icon = 'none') {
    wx.showToast({
      title: title,
      icon: icon,
      duration: 2000
    })
  },

  // 显示加载
  showLoading(title = '加载中...') {
    wx.showLoading({
      title: title,
      mask: true
    })
  },

  // 隐藏加载
  hideLoading() {
    wx.hideLoading()
  },

  // 显示确认对话框
  showModal(title, content) {
    return new Promise((resolve) => {
      wx.showModal({
        title: title,
        content: content,
        success: (res) => {
          resolve(res.confirm)
        }
      })
    })
  }
}) 